package com.xiia.dao;

import java.util.Date;
import java.util.List;

import com.xiia.util.Pager;
import com.xiia.vo.Org;

/**
 * 
 * @author 胡天天   2014-11-4
 * 分支机构dao
 *
 */

public class OrgDao extends BaseDao{
	private static UserDao userDao;
	public OrgDao(){
		userDao = new UserDao();
	}
	/**
	 * 添加分支机构
	 * @param org
	 * @return boolean
	 */
	public boolean addOrg(Org org){
		String sql="insert into t_org(orgName,link,addTime,lastUpdateTime,status,userId)"+
				"values(?,?,?,?,?,?)";
		Object[] params={org.getOrgName(),org.getLink(),new Date(),new Date(),1,
				         org.getUser().getUserId()};	
		int c=update(sql, params);
		if(c>0)
			return true;
		else
			return false;	
	}
	/**
	 * 修改org
	 * @param org
	 * @return boolean
	 */
	public boolean updateOrg(Org org){
		String sql = "update t_org set orgName=?,link=?,lastUpdateTime=?,userId=? where orgId=?";
		Object[] params = {org.getOrgName(),org.getLink(),new Date(),org.getUser().getUserId(),org.getOrgId()};
		int c = update(sql,params);
		if(c>0)
			return true;
		else
			return false;
	}
	/**
	 * 通过id来删除org
	 * @param org
	 * @return boolean
	 */
	public boolean deleteOrg(Org org){
		String sql = "delete from t_org where orgId=?";
		Object[] params = {org.getOrgId()};
		int c = update(sql,params);
		if(c>0)
			return true;
		else
			return false;
	}
	/**
	 * 查找所有的org
	 * @return List<Org>
	 */
	@SuppressWarnings("unchecked")
	public Pager findAllOrg(Pager page){
		String sql="select * from t_org limit ?,? ";
		Object[] params={(page.getCurrentPage()-1)*page.getPageSize(),page.getPageSize()};
		List<Org> org = find(sql,params,Org.class);
		for(Org o:org){
			o.setUser(userDao.getUserById(o.getUserId()));
		}
		page.setList(org);
		return page;
	}
	/**
	 * 得到t_org数据库中的数据总条数
	 * @return
	 */
	public int getAllCount(){
		String sql = "select count(*) count from t_org";
		int c = getCountFromTable(sql,null);
		return c;
	}
	/**
	 * 通过org的id来获得整个org对象
	 * @param org
	 * @return org
	 */
	public Org findOrgById(int orgId){
		String sql = "select * from t_org where orgId = ?";
		Object[] params = {orgId};
		Org org =(Org)findObject(sql,params,Org.class);
		return org;
	}
	/**
	 * 新建机构时判断该分类是否存在
	 * @param name
	 * @return
	 */
	public boolean isExist(String orgName){
		String sql = "select * from t_org where orgName=?";
		Object[] param = {orgName};
		Org org = (Org) findObject(sql,param,Org.class);
		if(org==null){
			return false;
		}
		else{
			return true;
		}
	}
}
